﻿using AutoMapper;
using System.Reflection;

namespace FrameworkCore.Extensions;

public static class MappingExpressions
{
    /// <summary>
    /// 忽略所有不匹配的属性。
    /// </summary>
    /// <param name="expression">配置表达式</param>
    /// <param name="from">源类型</param>
    /// <param name="to">目标类型</param>
    /// <returns></returns>
    public static IMappingExpression IgnoreAllNonExisting(this IMappingExpression expression, Type from, Type to)
    {
        var flags = BindingFlags.Public | BindingFlags.Instance;
        to.GetProperties(flags).Where(x => from.GetProperty(x.Name, flags) == null).ForEach(aProperty =>
        {
            expression.ForMember(aProperty.Name, opt => opt.Ignore());
        });

        return expression;
    }

    /// <summary>
    /// 忽略所有不匹配的属性。
    /// </summary>
    /// <typeparam name="TSource">源类型</typeparam>
    /// <typeparam name="TDestination">目标类型</typeparam>
    /// <param name="expression">配置表达式</param>
    /// <returns></returns>
    public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
    {
        Type from = typeof(TSource);
        Type to = typeof(TDestination);
        var flags = BindingFlags.Public | BindingFlags.Instance;
        to.GetProperties(flags).Where(x => from.GetProperty(x.Name, flags) == null).ForEach(aProperty =>
        {
            expression.ForMember(aProperty.Name, opt => opt.Ignore());
        });

        return expression;
    }
}
